<?php

namespace app\common\service;


use app\common\model\mysql\RuleModel;
use app\common\service\ConfigService;

class MenuService
{
    /**
     * 生成菜单
     * @param $rules
     * @return array
     */
    public static function menuTree($rules)
    {

        $menuHtml = [];
        foreach ($rules as $key => &$item) {
            // 获取组的权限集
            if (!empty($item)) {
                if ($item == '*') {
                    $menuList = RuleModel::getList(['status' => '1', 'is_menu' => '1'], ['id', 'name', 'route', 'parent_id', 'icon'], [], ['sort' => 'ASC', 'id' => 'ASC']);
                } else {
                    $ruleIds = explode(',', $item);
                    $where[] = ['status', '=', '1'];
                    $where[] = ['is_menu', '=', '1'];
                    $where[] = ['id', 'in', $ruleIds];
                    $menuList = RuleModel::getList($where, ['id', 'name', 'route', 'parent_id', 'icon'], [], ['sort' => 'ASC', 'id' => 'ASC']);
                }
                if (!empty($menuList)) {
                    // 获取菜单结构树
                    $menuList = getTree($menuList->toArray());
                    $menuHtml[$key] = self::getMenuHtml($menuList, $key);
                }
            }
        }
        return $menuHtml;
    }


    /**
     * 获取菜单结构树 html 代码
     * @param $menuList
     * @param $deep
     * @param $system_id
     * @return string
     */
    protected static function getMenuHtml($menuList, $deep = 2)
    {
        $menuHtml = "";
        $host = config('app.app_host');

        // 编辑菜单属性
        foreach ($menuList as $key => $menu) {
            // 跳转地址
            $redirectUrl = !empty($menu['route']) ? $host . '/' . $menu['route'] : 'javascript:;';

            // 图标
            $icon = !empty($menu["icon"]) ? "<i class='{$menu["icon"]}'></i>" : "";

            // 判断是否存在子菜单,存在就添加 子菜单的 类名
            if (!empty($menu['sub_item'])) {
                if ($deep == 2) {
                    $subMenuClass = 'nav nav-second-level';
                } else if ($deep == 3) {
                    $subMenuClass = 'nav nav-third-level';
                } else {
                    $subMenuClass = '';
                }
                $menuHtml .= "<li><a href='javascript:;'>{$icon}<span class='nav-label'>{$menu["name"]}</span><span class='fa arrow'></span></a><ul class='{$subMenuClass}'>";
                // 回调子菜单
                $menuHtml .= self::getMenuHtml($menu['sub_item'], $deep + 1);

                $menuHtml .= "</ul></li>";

            } else {

                if ($deep > 2) {
                    $menuHtml .= "<li><a href='{$redirectUrl}'>{$menu["name"]}</a></li>";
                } else {
                    $menuHtml .= "<li><a href='{$redirectUrl}'>{$icon}<span class='nav-label'>{$menu["name"]}</span></a></li>";
                }

            }
        }
        return $menuHtml;
    }
}